<script setup lang="ts">
import { isNullOrEmpty } from '@/utils/functions'
import { ref, reactive } from "vue";
import Motion from "../utils/motion";
import { message } from "@/utils/message";
import { registRules } from "../utils/rule";
import type { FormInstance } from "element-plus";
import { useVerifyCode } from "../utils/verifyCode";
import { $t, transformI18n } from "@/plugins/i18n";
import { useUserStoreHook } from "@/store/modules/user";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

import Lock from "@iconify-icons/ri/lock-fill";
// import Iphone from "@iconify-icons/ep/iphone";
// import User from "@iconify-icons/ri/user-3-fill";
import { getPhoneCode, registerUnit } from '@/api/user'
import { openProtocolContent, robotVerification } from '../utils/functions'
import { debounce, useGlobal } from "@pureadmin/utils";
import user from '@/assets/images/svg/user.svg'
import password from '@/assets/images/svg/password.svg'
import phone from '@/assets/images/svg/phone.svg'
import unity from '@/assets/images/svg/unity.svg'
import { getCaptcha } from "@/api/user";
import code from '@/assets/images/svg/code.svg'
const config = ref(useGlobal().$config)
const checked = ref(false);
const loading = ref(false);
const ruleForm = reactive({
  unityName: "",
  contactName: "",
  contactPhone: "",
  telCode: ''
});
const emits = defineEmits(["goLogin"]);
const ruleFormRef = ref<FormInstance>();
const { isDisabled, text, start, end } = useVerifyCode('regist');
const codeImg = ref("");

const onUpdate = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (checked.value) {
        registerUnit(ruleForm).then((res) => {
          message(res.msg, { type: "success", duration: 4000 });
          onBack()
        }).finally(() => {
          loading.value = false;
        })
      } else {
        loading.value = false;
        message(`请先勾选同意《${isNullOrEmpty(config.value.ProtocolName)}》`, { type: "warning" });
      }
    } else {
      loading.value = false;
      return fields;
    }
  });
};

function onBack() {
  emits("goLogin");
  // end();
  // useUserStoreHook().SET_CURRENTPAGE(0);
}
function getPhoneCodes() {
  ruleFormRef.value.validateField('contactPhone', isValid => {
    if (isValid) {
      getRobotVerification()
    }
  })
}
const getRobotVerification = debounce(() => {
  robotVerification({
    fun: getPhoneCode,
    param: { phone: ruleForm.contactPhone },
    successFun: () => {
      start(ruleFormRef.value, 'phone')
    }
  })
}, 500, true)
</script>

<template>
  <el-form ref="ruleFormRef" :model="ruleForm" :rules="registRules" size="large">
    <div class="login-form">
      <Motion>
        <el-form-item prop="unityName">
          <el-input v-model="ruleForm.unityName" clearable placeholder="请输入单位名称" :prefix-icon="useRenderIcon(unity)"
            v-bind="$attrs" />
        </el-form-item>
      </Motion>

      <Motion :delay="100">
        <el-form-item prop="contactName">
          <el-input v-model="ruleForm.contactName" clearable placeholder="请输入联系人" :prefix-icon="useRenderIcon(user)"
            v-bind="$attrs" />
        </el-form-item>
      </Motion>

      <Motion :delay="150">
        <el-form-item prop="contactPhone">
          <el-input v-model="ruleForm.contactPhone" clearable placeholder="请输入手机号" :prefix-icon="useRenderIcon(phone)"
            v-bind="$attrs" />
        </el-form-item>
      </Motion>
      <Motion :delay="200">
        <el-form-item prop="telCode">
          <div class="w-full flex justify-between">
            <el-input v-model="ruleForm.telCode" clearable placeholder="短信验证码" v-bind="$attrs"
              :prefix-icon="useRenderIcon(code)" />
            <!-- <el-button :disabled="isDisabled" class="ml-2 !border-[#fff]" @click="getPhoneCodes"> -->
            <el-button :disabled="isDisabled" class="ml-2 " @click="getPhoneCodes">
              <div class="text-[var(--el-color-primary)]">
                <!-- <div class="text-[#fff]"> -->
                {{ isNullOrEmpty(text.length > 0 ? text + ' s后重新获取' : '获取验证码') }}
              </div>
            </el-button>
          </div>
        </el-form-item>
      </Motion>
      <Motion :delay="250">
        <div class=" w-full flex-bc">
          <div class="flex-c">
            <el-checkbox v-model="checked">
              <div class="text-[#fff]">我已阅读并同意</div>
            </el-checkbox>
            <el-button link type="primary" style="--el-color-primary: #fe861c;--el-color-primary-light-5: #fe861c;"
              @click="openProtocolContent(config.ProtocolName, config.ProtocolContent)">
              《{{ isNullOrEmpty(config.ProtocolName) }}》
            </el-button>
          </div>
        </div>
      </Motion>

    </div>
    <Motion :delay="250">
      <el-form-item>
        <el-button class="w-full" size="default" type="primary" :loading="loading" @click="onUpdate(ruleFormRef)">
          注册
        </el-button>
      </el-form-item>
    </Motion>
    <div class="login-form">
      <Motion :delay="300">
        <el-form-item>
          <el-button class="w-full" size="default" @click="onBack">
            <el-text type="primary" class="text-[14px]">返回</el-text>
          </el-button>
        </el-form-item>
      </Motion>
    </div>
  </el-form>
</template>
